package com.dcits.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class RandomJsonGeneratorHelper {

    // 预定义字段类型规则
    public static final Map<String, ValueGenerator> DEFAULT_RULES = new HashMap<>();

    static {
        DEFAULT_RULES.put("name", () -> getRandomString(5) + " " + getRandomString(8));
        DEFAULT_RULES.put("age", () -> ThreadLocalRandom.current().nextInt(18, 80));
        DEFAULT_RULES.put("email", () -> getRandomString(8).toLowerCase() + "@example.com");
        DEFAULT_RULES.put("phone", () -> "1" + String.format("%010d", ThreadLocalRandom.current().nextLong(100_000_000_0L, 1_000_000_000_0L)));
        DEFAULT_RULES.put("timestamp", System::currentTimeMillis);
    }

    // 自定义字段生成器接口
    public interface ValueGenerator {
        Object generate();
    }

    /**
     * 生成随机JSON
     *
     * @param fieldRules 自定义字段规则（覆盖默认规则）
     * @param fieldCount 生成字段数量
     * @return 随机JSON字符串
     */
    public static String generate(Map<String, ValueGenerator> fieldRules, int fieldCount) {
        JSONObject json = new JSONObject();
        // 随机选择字段
        List<String> keys = new ArrayList<>(fieldRules.keySet());
        Collections.shuffle(keys);
        int count = Math.min(fieldCount, keys.size());

        for (int i = 0; i < count; i++) {
            String key = keys.get(i);
            json.put(key, fieldRules.get(key).generate());
        }
        return JSON.toJSONString(json, true); // 美化输出
    }

    // 辅助方法：生成随机字符串
    private static String getRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(ThreadLocalRandom.current().nextInt(chars.length())));
        }
        return sb.toString();
    }

}